package com.example.fileupload.task;

import com.example.fileupload.util.StorageHealthChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 存储维护定时任务
 */
@Slf4j
@Component
@EnableScheduling
@ConditionalOnProperty(name = "storage.maintenance.enabled", havingValue = "true", matchIfMissing = true)
public class StorageMaintenanceTask {
    
    @Autowired
    private StorageHealthChecker healthChecker;
    
    /**
     * 清理过期的健康检查缓存
     * 每5分钟执行一次
     */
    @Scheduled(fixedRate = 300000) // 5分钟
    public void cleanupExpiredHealthCache() {
        try {
            long maxAge = 300000; // 5分钟过期
            healthChecker.cleanupExpiredCache(maxAge);
            
            log.debug("清理过期健康检查缓存完成");
        } catch (Exception e) {
            log.error("清理健康检查缓存失败", e);
        }
    }
    
    /**
     * 定期检查所有存储策略的健康状态
     * 每30分钟执行一次
     */
    @Scheduled(fixedRate = 1800000) // 30分钟
    public void performPeriodicHealthCheck() {
        try {
            log.info("开始定期健康检查...");
            
            healthChecker.checkAllStoragesAsync()
                    .thenAccept(results -> {
                        long healthyCount = results.values().stream()
                                .mapToLong(result -> result.isHealthy() ? 1 : 0)
                                .sum();
                        
                        log.info("定期健康检查完成: {}/{} 个存储策略正常", 
                                healthyCount, results.size());
                        
                        // 记录异常的存储策略
                        results.forEach((type, result) -> {
                            if (!result.isHealthy()) {
                                log.warn("存储策略 {} 健康检查异常: {}", type, result.getMessage());
                            }
                        });
                    })
                    .exceptionally(throwable -> {
                        log.error("定期健康检查失败", throwable);
                        return null;
                    });
                    
        } catch (Exception e) {
            log.error("执行定期健康检查失败", e);
        }
    }
} 